<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css">


  <meta name="keywords" content="js,">





  <link rel="alternate" href="/atom.xml" title="zxlg's notes" type="application/atom+xml">




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1">






<meta name="description" content="一、属性Array.lengthlength属性的值是一个 0 到 2^32-1的整数。 你可以通过减小length属性的值来截短一个数组，但不能通过增大length属性的值来延长这个数组 Array.prototypeArray.prototype属性表示Array构造函数的原型;Array.prototype本身也是一个Array 二、方法Array.prototype.concat()不改变">
<meta name="keywords" content="js">
<meta property="og:type" content="article">
<meta property="og:title" content="Javascript中的Array对象总结">
<meta property="og:url" content="http://happylg.cn/2017/08/03/js-Array/index.html">
<meta property="og:site_name" content="zxlg&#39;s notes">
<meta property="og:description" content="一、属性Array.lengthlength属性的值是一个 0 到 2^32-1的整数。 你可以通过减小length属性的值来截短一个数组，但不能通过增大length属性的值来延长这个数组 Array.prototypeArray.prototype属性表示Array构造函数的原型;Array.prototype本身也是一个Array 二、方法Array.prototype.concat()不改变">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-08-19T06:37:33.865Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Javascript中的Array对象总结">
<meta name="twitter:description" content="一、属性Array.lengthlength属性的值是一个 0 到 2^32-1的整数。 你可以通过减小length属性的值来截短一个数组，但不能通过增大length属性的值来延长这个数组 Array.prototypeArray.prototype属性表示Array构造函数的原型;Array.prototype本身也是一个Array 二、方法Array.prototype.concat()不改变">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://happylg.cn/2017/08/03/js-Array/">





  <title>Javascript中的Array对象总结 | zxlg's notes</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zxlg's notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description"></h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://happylg.cn/2017/08/03/js-Array/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zxlg">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zxlg's notes">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Javascript中的Array对象总结</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-03T18:23:35+08:00">
                2017-08-03
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2017-08-19T14:37:33+08:00">
                2017-08-19
              </time>
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Javascript/" itemprop="url" rel="index">
                    <span itemprop="name">Javascript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2017/08/03/js-Array/" class="leancloud_visitors" data-flag-title="Javascript中的Array对象总结">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="一、属性"><a href="#一、属性" class="headerlink" title="一、属性"></a>一、属性</h1><h2 id="Array-length"><a href="#Array-length" class="headerlink" title="Array.length"></a>Array.length</h2><p><code>length</code>属性的值是一个 0 到 2^32-1的整数。</p>
<p>你可以通过减小<code>length</code>属性的值来截短一个数组，但不能通过增大<code>length</code>属性的值来延长这个数组</p>
<h2 id="Array-prototype"><a href="#Array-prototype" class="headerlink" title="Array.prototype"></a>Array.prototype</h2><p><code>Array.prototype</code>属性表示<code>Array</code>构造函数的原型;<code>Array.prototype</code>本身也是一个<code>Array</code></p>
<h1 id="二、方法"><a href="#二、方法" class="headerlink" title="二、方法"></a>二、方法</h1><h2 id="Array-prototype-concat"><a href="#Array-prototype-concat" class="headerlink" title="Array.prototype.concat()"></a>Array.prototype.concat()</h2><p><strong>不改变数组</strong></p>
<h3 id="语法"><a href="#语法" class="headerlink" title="语法"></a>语法</h3><pre><code>var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
</code></pre><h3 id="参数"><a href="#参数" class="headerlink" title="参数"></a>参数</h3><p><code>valueN</code>需要与原数组合并的数组或非数组值。详见下文。</p>
<h3 id="返回值"><a href="#返回值" class="headerlink" title="返回值"></a>返回值</h3><p>新的<code>Array</code>实例。</p>
<h3 id="描述"><a href="#描述" class="headerlink" title="描述"></a>描述</h3><p><code>concat</code>方法将创建一个新的数组，然后将调用它的对象(<code>this</code>指向的对象)中的元素以及所有参数中的数组类型的参数中的元素以及非数组类型的参数本身按照顺序放入这个新数组,并返回该数组.</p>
<p><code>concat</code>方法并不修改调用它的对象(<code>this</code>指向的对象) 和参数中的各个数组本身的值,而是将他们的每个元素拷贝一份放在组合成的新数组中.原数组中的元素有两种被拷贝的方式:</p>
<ul>
<li>对象引用(非对象直接量):<code>concat</code>方法会复制对象引用放到组合的新数组里,原数组和新数组中的对象引用都指向同一个实际的对象,所以,当实际的对象被修改时,两个数组也同时会被修改.</li>
<li>字符串和数字(是原始值,而不是包装原始值的<code>String</code>和<code>Number</code>对象):<code>concat</code>方法会复制字符串和数字的值放到新数组里</li>
</ul>
<a id="more"></a>
<h2 id="Array-prototype-filter"><a href="#Array-prototype-filter" class="headerlink" title="Array.prototype.filter()"></a>Array.prototype.filter()</h2><h3 id="语法-1"><a href="#语法-1" class="headerlink" title="语法"></a>语法</h3><pre><code>var new_array = arr.filter(callback[, thisArg])
</code></pre><h3 id="参数-1"><a href="#参数-1" class="headerlink" title="参数"></a>参数</h3><p><code>callback</code>用来测试数组的每个元素的函数。调用时使用参数<code>(element, index, array)</code>。返回<code>true</code>表示保留该元素（通过测试），<code>false</code>则不保留。<br><code>thisArg</code>可选。执行<code>callback</code>时的用于<code>this</code>的值。</p>
<h3 id="返回值-1"><a href="#返回值-1" class="headerlink" title="返回值"></a>返回值</h3><p>一个新的通过测试的元素的集合的数组</p>
<h3 id="描述-1"><a href="#描述-1" class="headerlink" title="描述"></a>描述</h3><p><code>filter</code>为数组中的每个元素调用一次<code>callback</code>函数，并利用所有使得<code>callback</code>返回<code>true</code>或等价于<code>true</code>的值的元素创建一个新数组。<code>callback</code>只会在已经赋值的索引上被调用，对于那些已经被删除或者从未被赋值的索引不会被调用。那些没有通过<code>callback</code>测试的元素会被跳过，不会被包含在新数组中。<br><code>callback</code>被调用时传入三个参数：</p>
<ol>
<li>元素的值</li>
<li>元素的索引</li>
<li>被遍历的数组</li>
</ol>
<p>如果为<code>filter</code>提供一个<code>thisArg</code>参数，则它会被作为<code>callback</code>被调用时的<code>this</code>值。否则，<code>callback</code>的<code>this</code>值在非严格模式下将是全局对象，严格模式下为<code>undefined</code>。</p>
<p><strong>filter不会改变原数组。</strong><br><code>filter</code>遍历的元素范围在第一次调用<code>callback</code>之前就已经确定了。在调用<code>filter</code>之后被添加到数组中的元素不会被filter遍历到。如果已经存在的元素被改变了，则他们传入<code>callback</code>的值是<code>filter</code>遍历到它们那一刻的值。<strong>被删除或从来未被赋值的元素不会被遍历到。</strong></p>
<h2 id="Array-prototype-find"><a href="#Array-prototype-find" class="headerlink" title="Array.prototype.find()"></a>Array.prototype.find()</h2><h2 id="Array-prototype-forEach"><a href="#Array-prototype-forEach" class="headerlink" title="Array.prototype.forEach()"></a>Array.prototype.forEach()</h2><h3 id="语法-2"><a href="#语法-2" class="headerlink" title="语法"></a>语法</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">array.forEach(callback(currentValue, index, array)&#123;</span><br><span class="line">	//do something</span><br><span class="line">&#125;, this)</span><br><span class="line">array.forEach(callback[, thisArg])</span><br></pre></td></tr></table></figure>
<h3 id="参数-2"><a href="#参数-2" class="headerlink" title="参数"></a>参数</h3><p><code>callback</code>为数组中每个元素执行的函数，该函数接收三个参数：</p>
<ul>
<li><code>currentValue</code>(当前值)数组中正在处理的当前元素。</li>
<li><code>index</code>(索引)数组中正在处理的当前元素的索引。</li>
<li><code>array`</code>forEach()`方法正在操作的数组。</li>
</ul>
<p><code>thisArg</code>可选参数。当执行回调 函数时用作<code>this</code>的值(参考对象)。</p>
<h3 id="返回值-2"><a href="#返回值-2" class="headerlink" title="返回值"></a>返回值</h3><p><code>undefined</code></p>
<h3 id="描述-2"><a href="#描述-2" class="headerlink" title="描述"></a>描述</h3><p><code>forEach</code>方法按升序为数组中含有效值的每一项执行一次<code>callback</code>函数，那些已删除（使用<code>delete</code>方法等情况）或者未初始化的项将被跳过（但不包括那些值为<code>undefined</code>的项）（例如在稀疏数组上）。<br><code>callback</code>函数会被依次传入三个参数：</p>
<ol>
<li>数组当前项的值</li>
<li>数组当前项的索引</li>
<li>数组对象本身</li>
</ol>
<p>如果给<code>forEach</code>传递了<code>thisArg</code>参数，当调用时，它将被传给<code>callback</code>函数，作为它的<code>this</code>值。否则，将会传入<code>undefined</code>作为它的<code>this</code>值。<code>callback</code>函数最终可观察到<code>this</code>值，这取决于函数观察到<code>this</code>的常用规则。<br><code>forEach</code>遍历的范围在第一次调用<code>callback</code>前就会确定。调用<code>forEach</code>后添加到数组中的项不会被<code>callback</code>访问到。如果已经存在的值被改变，则传递给<code>callback</code>的值是<code>forEach</code>遍历到他们那一刻的值。已删除的项不会被遍历到。如果已访问的元素在迭代时被删除了(例如使用<code>shift()</code>) ，之后的元素将被跳过.<br><code>forEach()</code>为每个数组元素执行<code>callback</code>函数；不像<code>map()</code>或者<code>reduce()</code> ，它总是返回<code>undefined</code>值，并且不可链式调用。典型用例是在一个链的最后执行副作用。</p>
<h2 id="Array-prototype-indexOf"><a href="#Array-prototype-indexOf" class="headerlink" title="Array.prototype.indexOf()"></a>Array.prototype.indexOf()</h2><p>indexOf()方法返回在数组中可以找到一个给定元素的第一个索引，如果不存在，则返回-1。</p>
<h3 id="语法-3"><a href="#语法-3" class="headerlink" title="语法"></a>语法</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">arr.indexOf(searchElement)</span><br><span class="line">arr.indexOf(searchElement[, fromIndex = 0])</span><br></pre></td></tr></table></figure>
<h3 id="参数-3"><a href="#参数-3" class="headerlink" title="参数"></a>参数</h3><p><code>searchElement</code>要查找的元素。<br><code>fromIndex</code>开始查找的位置。如果该索引值大于或等于数组长度，意味着不会在数组里查找，返回-1。如果参数中提供的索引值是一个负值，则将其作为数组末尾的一个抵消，即-1表示从最后一个元素开始查找，-2表示从倒数第二个元素开始查找，以此类推。注意：如果参数中提供的索引值是一个负值，仍然从前向后查询数组。如果抵消后的索引值仍小于0，则整个数组都将会被查询。其默认值为0.</p>
<h3 id="返回值-3"><a href="#返回值-3" class="headerlink" title="返回值"></a>返回值</h3><p>首个被找到的元素在数组中的索引位置;若没有找到则返回-1</p>
<h2 id="Array-prototype-join"><a href="#Array-prototype-join" class="headerlink" title="Array.prototype.join()"></a>Array.prototype.join()</h2><p><strong>不改变数组</strong></p>
<h2 id="Array-prototype-keys"><a href="#Array-prototype-keys" class="headerlink" title="Array.prototype.keys()"></a>Array.prototype.keys()</h2><h2 id="Array-prototype-values"><a href="#Array-prototype-values" class="headerlink" title="Array.prototype.values()"></a>Array.prototype.values()</h2><h2 id="Array-prototype-entries"><a href="#Array-prototype-entries" class="headerlink" title="Array.prototype.entries()"></a>Array.prototype.entries()</h2><h2 id="Array-prototype-pop"><a href="#Array-prototype-pop" class="headerlink" title="Array.prototype.pop()"></a>Array.prototype.pop()</h2><h2 id="Array-prototype-push"><a href="#Array-prototype-push" class="headerlink" title="Array.prototype.push()"></a>Array.prototype.push()</h2><h2 id="Array-prototype-shift"><a href="#Array-prototype-shift" class="headerlink" title="Array.prototype.shift()"></a>Array.prototype.shift()</h2><h2 id="Array-prototype-unshift"><a href="#Array-prototype-unshift" class="headerlink" title="Array.prototype.unshift()"></a>Array.prototype.unshift()</h2><h2 id="Array-prototype-map"><a href="#Array-prototype-map" class="headerlink" title="Array.prototype.map()"></a>Array.prototype.map()</h2><h3 id="语法-4"><a href="#语法-4" class="headerlink" title="语法"></a>语法</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">let array = arr.map(function callback(currentValue, index, array) &#123; </span><br><span class="line">   	// Return element for new_array </span><br><span class="line">&#125;[, thisArg])</span><br></pre></td></tr></table></figure>
<h3 id="参数-4"><a href="#参数-4" class="headerlink" title="参数"></a>参数</h3><p><code>callback</code>生成新数组元素的函数，使用三个参数：<br><code>currentValue`</code>callback<code>的第一个参数，数组中正在处理的当前元素。</code>index<code>callback`的第二个参数，数组中正在处理的当前元素的索引。
`array</code>callback<code>的第三个参数，</code>map<code>方法被调用的数组。</code>thisArg<code>可选的。执行</code>callback<code>函数时,使用的</code>this`值。</p>
<h3 id="返回值-4"><a href="#返回值-4" class="headerlink" title="返回值"></a>返回值</h3><p>一个新数组，每个元素都是回调函数的结果。</p>
<h3 id="描述-3"><a href="#描述-3" class="headerlink" title="描述"></a>描述</h3><p><code>map</code>方法会给原数组中的每个元素都按顺序调用一次<code>callback</code>函数。<code>callback</code>每次执行后的返回值（包括<code>undefined</code>）组合起来形成一个新数组。<code>callback</code>函数只会在有值的索引上被调用；那些从来没被赋过值或者使用<code>delete</code>删除的索引则不会被调用。<br><code>callback</code>函数会被自动传入三个参数：数组元素，元素索引，原数组本身。<br>如果<code>thisArg</code>参数有值，则每次<code>callback</code>函数被调用的时候，<code>this</code>都会指向<code>thisArg</code>参数上的这个对象。如果省略了<code>thisArg</code>参数,或者赋值为<code>null</code>或<code>undefined</code>，则<code>this</code>指向全局对象。<br><strong>map不修改调用它的原数组本身</strong>（当然可以在<code>callback</code>执行时改变原数组）。<br>使用<code>map</code>方法处理数组时，数组元素的范围是在<code>callback</code>方法第一次调用之前就已经确定了。在<code>map</code>方法执行的过程中：原数组中新增加的元素将不会被<code>callback</code>访问到；若已经存在的元素被改变或删除了，则它们的传递到<code>callback</code>的值是<code>map</code>方法遍历到它们的那一时刻的值；<strong>而被删除的元素将不会被访问到。</strong></p>
<h2 id="Array-prototype-reduce"><a href="#Array-prototype-reduce" class="headerlink" title="Array.prototype.reduce()"></a>Array.prototype.reduce()</h2><h3 id="语法-5"><a href="#语法-5" class="headerlink" title="语法"></a>语法</h3><pre><code>array.reduce(function(accumulator, currentValue, currentIndex, array), initialValue)
</code></pre><h3 id="参数-5"><a href="#参数-5" class="headerlink" title="参数"></a>参数</h3><p><code>callback</code>执行数组中每个值的函数，包含四个参数<br><code>accumulator</code>上一次调用回调返回的值，或者是提供的初始值<code>initialValue</code><br><code>currentValue</code>数组中正在处理的元素<br><code>currentIndex</code>数据中正在处理的元素索引,如果提供了<code>initialValue</code>,从0开始;否则从1开始<br><code>array</code>调用<code>reduce</code>的数组<br><code>initialValue</code>可选项，其值用于第一次调用<code>callback</code>的第一个参数。如果没有设置初始值，则将数组中的第一个元素作为初始值。<strong>空数组调用<code>reduce</code>时没有设置初始值将会报错。</strong></p>
<h3 id="返回值-5"><a href="#返回值-5" class="headerlink" title="返回值"></a>返回值</h3><p>函数累计处理的结果</p>
<h3 id="描述-4"><a href="#描述-4" class="headerlink" title="描述"></a>描述</h3><p><code>reduce</code>为数组中的每一个元素依次执行回调函数，不包括数组中被删除或从未被赋值的元素，接受四个参数：<br><code>accumulator</code>初始值（或者上一次回调函数的返回值）<br><code>currentValue</code>当前元素值<br><code>currentIndex</code>当前索引<br><code>array</code>调用<code>reduce</code>的数组。<br>回调函数第一次执行时，<code>accumulator</code>和<code>currentValue</code>的取值有两种情况：调用<code>reduce</code>时提供<code>initialValue</code>，<code>accumulator</code>取值为<code>initialValue</code>，<code>currentValue</code>取数组中的第一个值；没有提供<code>initialValue</code>，<code>accumulator</code>取数组中的第一个值，<code>currentValue</code>取数组中的第二个值。<br><strong>注意</strong>: </p>
<ol>
<li>不提供<code>initialValue</code>，<code>reduce</code>会从索引1的地方开始执行<code>callback</code>方法，跳过第一个索引。提供<code>initialValue</code>，从索引0开始。</li>
<li>如果数组为空并且没有提供<code>initialValue</code>，会抛出<code>TypeError</code>。如果数组仅有一个元素（无论位置如何）并且没有提供<code>initialValue</code>，或者有提供<code>initialValue</code>但是数组为空，那么此唯一值将被返回并且<code>callback</code>不会被执行。</li>
</ol>
<h2 id="Array-prototype-reduceRight"><a href="#Array-prototype-reduceRight" class="headerlink" title="Array.prototype.reduceRight()"></a>Array.prototype.reduceRight()</h2><h2 id="Array-prototype-sort"><a href="#Array-prototype-sort" class="headerlink" title="Array.prototype.sort()"></a>Array.prototype.sort()</h2><p><strong>改变数组</strong></p>
<h2 id="Array-prototype-reverse"><a href="#Array-prototype-reverse" class="headerlink" title="Array.prototype.reverse()"></a>Array.prototype.reverse()</h2><p><strong>改变数组</strong></p>
<h2 id="Array-prototype-slice"><a href="#Array-prototype-slice" class="headerlink" title="Array.prototype.slice()"></a>Array.prototype.slice()</h2><p><strong>注意:’slice()’为浅拷贝,不改变数组</strong></p>
<h3 id="语法-6"><a href="#语法-6" class="headerlink" title="语法"></a>语法</h3><pre><code>arr.slice(begin,end)
</code></pre><h3 id="参数-6"><a href="#参数-6" class="headerlink" title="参数"></a>参数</h3><p><code>begin</code>可选，从索引处开始提取，默认为0。如果参数为负数-a，从倒数第a个元素开始提取。<code>slice(-2)</code>表示从倒数第二提取到倒数第一(包含最后一个元素)。<br><code>end</code>可选，从索引处结束提取。<code>slice(begin,end)</code>包含<code>begin</code>但不包含<code>end</code>。如果为负数表示在倒数第几个结束提取，slice(-2,-1),不包含最后一个。<br><code>end</code>省略或大于数组长度，一直提取到原数组末尾</p>
<h3 id="返回值-6"><a href="#返回值-6" class="headerlink" title="返回值"></a>返回值</h3><p>一个含有提取元素的新数组</p>
<h3 id="描述-5"><a href="#描述-5" class="headerlink" title="描述"></a>描述</h3><p><code>slice()</code>不会修改数组，只会浅拷贝，规则如下：</p>
<ul>
<li>对象引用(非对象直接量):<code>concat</code>方法会复制对象引用放到组合的新数组里,原数组和新数组中的对象引用都指向同一个实际的对象,所以,当实际的对象被修改时,两个数组也同时会被修改.</li>
<li>对于字符串、数字及布尔值来说（不是<code>String</code>、<code>Number</code>或者<code>Boolean</code>对象），<code>slice</code>会拷贝这些值到新的数组里。在别的数组里修改这些字符串或数字或是布尔值，将不会影响另一个数组。</li>
</ul>
<p>如果向两个数组任一中添加了新元素，则另一个不会受到影响。</p>
<h2 id="Array-prototype-splice"><a href="#Array-prototype-splice" class="headerlink" title="Array.prototype.splice()"></a>Array.prototype.splice()</h2><p><strong>改变数组，返回被删除元素组成的数组</strong></p>
<h1 id="参考文献"><a href="#参考文献" class="headerlink" title="参考文献"></a>参考文献</h1><ol>
<li><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array" target="_blank" rel="noopener">MDN</a></li>
</ol>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zxlg
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://happylg.cn/2017/08/03/js-Array/" title="Javascript中的Array对象总结">http://happylg.cn/2017/08/03/js-Array/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/js/" rel="tag"># js</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/03/js-String/" rel="next" title="Javascript中String对象总结">
                <i class="fa fa-chevron-left"></i> Javascript中String对象总结
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/04/js-equal/" rel="prev" title="Javascript相等性比较">
                Javascript相等性比较 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image" src="/uploads/avatar.png" alt="zxlg">
          <p class="site-author-name" itemprop="name">zxlg</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
           
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">63</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">22</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">96</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/zxlg1993" target="_blank" title="微博">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                    
                      微博
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://github.com/gongzhibin" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                    
                      GitHub
                    
                </a>
              </span>
            
          
        </div>

        
        
          <div class="cc-license motion-element" itemprop="license">
            <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
              <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons">
            </a>
          </div>
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#一、属性"><span class="nav-number">1.</span> <span class="nav-text">一、属性</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-length"><span class="nav-number">1.1.</span> <span class="nav-text">Array.length</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype"><span class="nav-number">1.2.</span> <span class="nav-text">Array.prototype</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#二、方法"><span class="nav-number">2.</span> <span class="nav-text">二、方法</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-concat"><span class="nav-number">2.1.</span> <span class="nav-text">Array.prototype.concat()</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法"><span class="nav-number">2.1.1.</span> <span class="nav-text">语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参数"><span class="nav-number">2.1.2.</span> <span class="nav-text">参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#返回值"><span class="nav-number">2.1.3.</span> <span class="nav-text">返回值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#描述"><span class="nav-number">2.1.4.</span> <span class="nav-text">描述</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-filter"><span class="nav-number">2.2.</span> <span class="nav-text">Array.prototype.filter()</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法-1"><span class="nav-number">2.2.1.</span> <span class="nav-text">语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参数-1"><span class="nav-number">2.2.2.</span> <span class="nav-text">参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#返回值-1"><span class="nav-number">2.2.3.</span> <span class="nav-text">返回值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#描述-1"><span class="nav-number">2.2.4.</span> <span class="nav-text">描述</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-find"><span class="nav-number">2.3.</span> <span class="nav-text">Array.prototype.find()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-forEach"><span class="nav-number">2.4.</span> <span class="nav-text">Array.prototype.forEach()</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法-2"><span class="nav-number">2.4.1.</span> <span class="nav-text">语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参数-2"><span class="nav-number">2.4.2.</span> <span class="nav-text">参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#返回值-2"><span class="nav-number">2.4.3.</span> <span class="nav-text">返回值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#描述-2"><span class="nav-number">2.4.4.</span> <span class="nav-text">描述</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-indexOf"><span class="nav-number">2.5.</span> <span class="nav-text">Array.prototype.indexOf()</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法-3"><span class="nav-number">2.5.1.</span> <span class="nav-text">语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参数-3"><span class="nav-number">2.5.2.</span> <span class="nav-text">参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#返回值-3"><span class="nav-number">2.5.3.</span> <span class="nav-text">返回值</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-join"><span class="nav-number">2.6.</span> <span class="nav-text">Array.prototype.join()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-keys"><span class="nav-number">2.7.</span> <span class="nav-text">Array.prototype.keys()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-values"><span class="nav-number">2.8.</span> <span class="nav-text">Array.prototype.values()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-entries"><span class="nav-number">2.9.</span> <span class="nav-text">Array.prototype.entries()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-pop"><span class="nav-number">2.10.</span> <span class="nav-text">Array.prototype.pop()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-push"><span class="nav-number">2.11.</span> <span class="nav-text">Array.prototype.push()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-shift"><span class="nav-number">2.12.</span> <span class="nav-text">Array.prototype.shift()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-unshift"><span class="nav-number">2.13.</span> <span class="nav-text">Array.prototype.unshift()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-map"><span class="nav-number">2.14.</span> <span class="nav-text">Array.prototype.map()</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法-4"><span class="nav-number">2.14.1.</span> <span class="nav-text">语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参数-4"><span class="nav-number">2.14.2.</span> <span class="nav-text">参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#返回值-4"><span class="nav-number">2.14.3.</span> <span class="nav-text">返回值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#描述-3"><span class="nav-number">2.14.4.</span> <span class="nav-text">描述</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-reduce"><span class="nav-number">2.15.</span> <span class="nav-text">Array.prototype.reduce()</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法-5"><span class="nav-number">2.15.1.</span> <span class="nav-text">语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参数-5"><span class="nav-number">2.15.2.</span> <span class="nav-text">参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#返回值-5"><span class="nav-number">2.15.3.</span> <span class="nav-text">返回值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#描述-4"><span class="nav-number">2.15.4.</span> <span class="nav-text">描述</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-reduceRight"><span class="nav-number">2.16.</span> <span class="nav-text">Array.prototype.reduceRight()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-sort"><span class="nav-number">2.17.</span> <span class="nav-text">Array.prototype.sort()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-reverse"><span class="nav-number">2.18.</span> <span class="nav-text">Array.prototype.reverse()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-slice"><span class="nav-number">2.19.</span> <span class="nav-text">Array.prototype.slice()</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法-6"><span class="nav-number">2.19.1.</span> <span class="nav-text">语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参数-6"><span class="nav-number">2.19.2.</span> <span class="nav-text">参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#返回值-6"><span class="nav-number">2.19.3.</span> <span class="nav-text">返回值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#描述-5"><span class="nav-number">2.19.4.</span> <span class="nav-text">描述</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-splice"><span class="nav-number">2.20.</span> <span class="nav-text">Array.prototype.splice()</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#参考文献"><span class="nav-number">3.</span> <span class="nav-text">参考文献</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zxlg</span>

  
</div>


  <div class="powered-by">
    由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
  </div>

  <span class="post-meta-divider">|</span>

  <div class="theme-info">
    主题 &mdash;
    <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
      NexT.Mist
    </a>
  </div>


        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  


  

    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://happylg.cn/2017/08/03/js-Array/';
          this.page.identifier = '2017/08/03/js-Array/';
          this.page.title = 'Javascript中的Array对象总结';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://happylg.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  













  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("hR3ATs8pfE23chEpVt6B1ovg-gzGzoHsz", "oIbFkcd43Cjd1FqkymLs6o2D");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>
